package com.mogujie.tt.imservice.manager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.DB.sp.RegisterSp;
import com.mogujie.tt.R;
import com.mogujie.tt.config.MessageConstant;
import com.mogujie.tt.config.RegisterConstant;
import com.mogujie.tt.config.SysConstant;
import com.mogujie.tt.customview.control.CustomDot;
import com.mogujie.tt.customview.control.PhoneVerificationCode;
import com.mogujie.tt.imservice.entity.ImageMessage;
import com.mogujie.tt.imservice.event.ConcurrentUserDetailsEvent;
import com.mogujie.tt.imservice.event.RegisterEvent;
import com.mogujie.tt.imservice.event.UserInfoEvent;
import com.mogujie.tt.imservice.service.LoadImageService;
import com.mogujie.tt.utils.FileUtil;
import com.mogujie.tt.utils.HttpUtilsApache;
import com.mogujie.tt.utils.JsonUtil;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import de.greenrobot.event.EventBus;

/**
 * Created by user on 2015/9/11.
 */
public class IMRegisterManager extends IMManager {

    private String[] items = new String[] { "选择本地图片", "拍照" };
    private Uri uritempFile;


    /**单例模式*/
    private static IMRegisterManager inst = new IMRegisterManager();
    public static IMRegisterManager instance() {
        return inst;
    }


    /**注册参数 */
    private String registerUserName;
    private String registerPwd;

    @Override
    public void doOnStart() {

    }

    @Override
    public void reset() {

    }

    /**
     * 实现自身的事件驱动
     * @param event
     */
    public void triggerEvent(RegisterEvent.UserName event) {

        EventBus.getDefault().postSticky(event);
    }
    public void triggerEvent(RegisterEvent.UserPassWord event) {

        EventBus.getDefault().postSticky(event);
    }

    //发送验证码
    public void triggerEvent(RegisterEvent.AuthCode event) {

        EventBus.getDefault().postSticky(event);
    }

    //同步昵称个性化头像事件
    public void triggerEvent(ConcurrentUserDetailsEvent.ConcurrentNicknameEvent event) {

        EventBus.getDefault().postSticky(event);
    }

    //更新我的页面
    public void triggerEvent(RegisterEvent.MyPage event){
        EventBus.getDefault().postSticky(event);
    }

    //同步详细信息
    public void triggerEvent(UserInfoEvent event) {

        EventBus.getDefault().postSticky(event);
    }

    /**
     *  判断用户是否已被注册
     */
    public void whetherUserRegistered(String registerUserName ,Context context,PhoneVerificationCode mPhoneVerificationCode){

        this.registerUserName =registerUserName;

        new UserExistTask( this.registerUserName,context,mPhoneVerificationCode).executeOnExecutor(Executors.newCachedThreadPool());

    }

    /**
     * 判断注册密码是否一致
     */
    public void passwordsConsistent(String pwd1,String pwd2){

        if(pwd1.equals(pwd2)){
          triggerEvent(RegisterEvent.UserPassWord.USER_PASSWORD_SAME);
        }else{
            triggerEvent(RegisterEvent.UserPassWord.USER_PASSWORD_NO_SAME);
        }
    }
    /**
     * 提交注册用户的密码
     */
    public void authCodeConsistent(Context context){

        new SubmitUserPasswordTask(context).executeOnExecutor(Executors.newCachedThreadPool());
    }

    /**
     * 提交用户的详细信息
     */
    public void  submiUserDetails(Context context){
        new SubmitUserDetailsTask(context).executeOnExecutor(Executors.newCachedThreadPool());
    }


    /**
     * 显示设置头像的对话框
     * @param context
     */
    public void showDialog(final Context context) {

        final Activity m;
        m = (Activity)context;
        new AlertDialog.Builder(m)
                .setTitle("设置头像")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:// 设置本地图像
                                Intent intentFromGallery = new Intent();
                                intentFromGallery.setType("image/*"); // 设置文件类型
                                intentFromGallery
                                        .setAction(Intent.ACTION_GET_CONTENT);
                                m.startActivityForResult(intentFromGallery,
                                        RegisterConstant.IMAGE_REQUEST_CODE);//直接调用相册的来裁剪
                                break;
                            case 1:

                                Intent intentFromCapture = new Intent(
                                        MediaStore.ACTION_IMAGE_CAPTURE);//调用相机
                                // 判断存储卡是否可以用，可用进行存储
                                if (FileUtil.hasSdcard()) {
                                    intentFromCapture.putExtra(
                                            MediaStore.EXTRA_OUTPUT,
                                            Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                                                    RegisterConstant.IMAGE_FILE_NAME)));
                                }
                                m.startActivityForResult(intentFromCapture,
                                        RegisterConstant.CAMERA_REQUEST_CODE);
                                break;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    /**
     * 裁剪图片方法实现
     * @param uri
     * @param context
     */
    public void startPhotoZoom(Uri uri,final Context context) {

        final Activity m;
        m = (Activity)context;
        //调用系统截图方式
        Intent intent = new Intent("com.android.camera.action.CROP");

        // crop为true是设置在开启的intent中设置显示的view可以剪裁 
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        /**  
              * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）  
              * 故将图片保存在Uri中，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题  
              */
        //	intent.putExtra("return-data", true);

        //uritempFile为Uri类变量，实例化uritempFile
        uritempFile = Uri.parse("file://" + "/" +RegisterConstant.PHOTO_PATH + RegisterConstant.IMAGE_FILE_TAILOR_NAME);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        m.startActivityForResult(intent, 2);
    }


    /**
     * 保存裁剪之后的图片数据
     * @param data
     * @param context
     * @param mFace
     */
    public void getImageToView(Intent data,final Context context,final ImageView mFace ) {
        Activity m;
        m = (Activity)context;
        Bundle extras = data.getExtras();
        if (extras != null) {
            //将Uri图片转换为Bitmap
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(m.getContentResolver().openInputStream(uritempFile));
                mFace.setImageBitmap(bitmap);//设置头像
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }



    /**
     * 异步请求用户是否存在
     */
    private class UserExistTask extends AsyncTask<Void,Void,String>{

        Context context;
        String userName;
        JSONObject request;
        JSONObject rtjson;//json对象
        String newMessageInfo = "";
        ProgressDialog mProgressDialog;
        PhoneVerificationCode mPhoneVerificationCode;
        public UserExistTask(String userName,Context context,PhoneVerificationCode mPhoneVerificationCode) {
            this.context = context;
            this.userName = userName;
            this.mPhoneVerificationCode =mPhoneVerificationCode;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog =new ProgressDialog(context);
            mProgressDialog.setMessage("正在检查用户是否已经注册...");
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            Map<String, Object> parms = new HashMap<String ,Object>();
            parms.put("name", userName);
            request = new JSONObject();//新建json格式
            request = JsonUtil.jsonRequest(RegisterConstant.SERVER_NAME,RegisterConstant.REQUEST_USER_EXISTS,parms);
            String jsonstr = HttpUtilsApache.usHttpPostJson(RegisterConstant.SERVER_PATH, request);
            JsonUtil jsonUtil=new JsonUtil();//建立json验证
            if(jsonstr.length()>3){
                rtjson=jsonUtil.getOutputJson(jsonstr);
                Log.v("","rtjson = "+rtjson);

            }else{
                newMessageInfo=HttpUtilsApache.errorMsg(jsonstr);//打印出错信息
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if("".equals(newMessageInfo) || newMessageInfo==null)
            {
                if(rtjson!=null && !"".equals(rtjson)){

                    try {
                        String responseCode=rtjson.getString("response_code").toString();
                        if("1".equals(responseCode)) {
                          //  Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            RegisterConstant.user_name =userName;//得到用户名
                          //  Log.v("2222222222","RegisterConstant.user_name = "+ RegisterConstant.user_name);
                         //   triggerEvent(RegisterEvent.UserName.USER_NAME_AVAILABLE);
                            mPhoneVerificationCode.methods();
                            new MessageAuthenticationTask(context,userName).executeOnExecutor(Executors.newCachedThreadPool());//读取手机验证码
                        }else if("-1".equals(responseCode)) {
                          //  Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            Toast.makeText(context,"用户已存在",Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {}
                }
            }
            else {

                Toast.makeText(context, newMessageInfo, Toast.LENGTH_SHORT).show();
            }
            mProgressDialog.dismiss();
        }
    }

    /**
     * 请求手机短信短信验证码
     */
    private class  MessageAuthenticationTask  extends AsyncTask<Void,Void,String>{

        Context context;
        String userName;
        JSONObject request;
        JSONObject rtjson;//json对象
        String newMessageInfo = "";

        public MessageAuthenticationTask(Context context,String userName) {
            this.context = context;
            this.userName = userName;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Void... params) {
            Map<String, Object> parms = new HashMap<String ,Object>();
            parms.put("to_rece",userName);//提交手机号
            parms.put("msg_type","");
            request = new JSONObject();//新建json格式
            request = JsonUtil.jsonRequest(RegisterConstant.SMS_SERVER_NAME,RegisterConstant.REQUEST_USER_PHONE_CODE,parms);
            String jsonstr = HttpUtilsApache.usHttpPostJson(RegisterConstant.SERVER_PATH, request);
            JsonUtil jsonUtil=new JsonUtil();//建立json验证
            if(jsonstr.length()>3){
                rtjson=jsonUtil.getOutputJson(jsonstr);
                Log.v("","rtjson = "+rtjson);

            }else{
                newMessageInfo=HttpUtilsApache.errorMsg(jsonstr);//打印出错信息
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if("".equals(newMessageInfo) || newMessageInfo==null)
            {
                if(rtjson!=null && !"".equals(rtjson)){

                    try {
                        String responseCode=rtjson.getString("response_code").toString();
                        if("1".equals(responseCode)) {
                          //   Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            Toast.makeText(context,"短信已发送，请注意查收",Toast.LENGTH_LONG).show();
                        }else if("-1".equals(responseCode)) {
                         //   Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            Toast.makeText(context,"短信发送失败",Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {}
                }
            }
            else {
                Toast.makeText(context, newMessageInfo, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 提交用户密码
     */
    private class   SubmitUserPasswordTask  extends AsyncTask<Void,Void,String>{

        Context context;
        JSONObject request;
        JSONObject rtjson;//json对象
        String newMessageInfo = "";
        public SubmitUserPasswordTask(Context context) {
            this.context = context;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Void... params) {
            Map<String, Object> parms = new HashMap<String ,Object>();
//            Log.v("222222222222","name ="+RegisterConstant.user_name);
//            Log.v("222222222222","code ="+RegisterConstant.user_auth);
//            Log.v("222222222222","password ="+RegisterConstant.user_password);
            parms.put("name", RegisterConstant.user_name);//提交手机号
            parms.put("code",RegisterConstant.user_auth);//提交验证码
            parms.put("password",RegisterConstant.user_password);//提交用户密码
            request = new JSONObject();//新建json格式
            request = JsonUtil.jsonRequest(RegisterConstant.SERVER_NAME,RegisterConstant.SUBMIT_USER_PASSWORD,parms);
         //   Log.v("2222222222222222","request = "+request);
            String jsonstr = HttpUtilsApache.usHttpPostJson(RegisterConstant.SERVER_PATH, request);
         //   Log.v("2222222222222222","jsonstr = "+jsonstr);
            JsonUtil jsonUtil=new JsonUtil();//建立json验证
            if(jsonstr.length()>3){
                rtjson=jsonUtil.getOutputJson(jsonstr);
                Log.v("","rtjson = "+rtjson);

            }else{
                newMessageInfo=HttpUtilsApache.errorMsg(jsonstr);//打印出错信息
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if("".equals(newMessageInfo) || newMessageInfo==null)
            {
                if(rtjson!=null && !"".equals(rtjson)){

                    try {
                        String responseCode=rtjson.getString("response_code").toString();
                        if("1".equals(responseCode)) {
                            triggerEvent(RegisterEvent.AuthCode.AUTH_CODE_SAME);
                        //    Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                              Toast.makeText(context,"用户注册成功,请尽快完善详细信息",Toast.LENGTH_LONG).show();
                        }else if("-1".equals(responseCode)) {
                       //     Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            Toast.makeText(context,"用户注册失败",Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {}
                }
            }
            else {
                Toast.makeText(context, newMessageInfo, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 提交用户详细信息异步任务
     */
    private class   SubmitUserDetailsTask  extends AsyncTask<Void,Void,String>{

        Context context;
        JSONObject request;
        JSONObject rtjson;//json对象
        String newMessageInfo = "";
        public SubmitUserDetailsTask(Context context) {
            this.context = context;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Void... params) {
            Map<String, Object> parms = new HashMap<String ,Object>();

            parms.put("id", LoginSp.instance().getLoginIdentity().getLoginId());
            parms.put("phone", RegisterSp.instance().getSpDetailedInfo().getDetailedMobilePhone().toString().trim());
            parms.put("sex",RegisterSp.instance().getSpDetailedInfo().getDetailedSex());
            parms.put("nick",RegisterSp.instance().getSpDetailedInfo().getDetailedNickName().toString().trim());
            parms.put("email",RegisterSp.instance().getSpDetailedInfo().getDetailedEmail().toString().trim());
        //    parms.put("avatar",RegisterSp.instance().getSpDetailedInfo().getDetailedHeadPortrait().toString().trim());
            parms.put("avatar","");
            request = new JSONObject();//新建json格式
            request = JsonUtil.jsonRequest(RegisterConstant.SERVER_NAME,RegisterConstant.SUBMIT_USER_DETAILED,parms);
            String jsonstr = HttpUtilsApache.usHttpPostJson(RegisterConstant.SERVER_PATH, request);
            JsonUtil jsonUtil=new JsonUtil();//建立json验证
            if(jsonstr.length()>3){
                rtjson=jsonUtil.getOutputJson(jsonstr);
                Log.v("","rtjson = "+rtjson);
            }else{
                newMessageInfo=HttpUtilsApache.errorMsg(jsonstr);//打印出错信息
            }
            uploadPictures(context);//上传个性化头像
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if("".equals(newMessageInfo) || newMessageInfo==null)
            {
                if(rtjson!=null && !"".equals(rtjson)){

                    try {
                        String responseCode=rtjson.getString("response_code").toString();
                        if("1".equals(responseCode)) {
                            triggerEvent(RegisterEvent.AuthCode.AUTH_CODE_SAME);
                        //    triggerEvent(ConcurrentUserDetailsEvent.ConcurrentNicknameEvent.MODIFY_NICKNAME);
                        //    Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                            Toast.makeText(context,"用户修改详细信息成功",Toast.LENGTH_LONG).show();
                        }else if("-1".equals(responseCode)) {
                            Toast.makeText(context,rtjson.getString("response_desc").toString(),Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {}
                }
            }
            else {
                Toast.makeText(context, newMessageInfo, Toast.LENGTH_SHORT).show();
            }
        }
    }
    /**
     * 上传图片测试
     */
    private void  uploadPictures(Context context){
        //获取上传文件的路径
        String path =  RegisterConstant.PHOTO_PATH + RegisterConstant.IMAGE_FILE_TAILOR_NAME;
        File file = new File(path);
        if(!file.exists()){
            IMRegisterManager.instance().triggerEvent(ConcurrentUserDetailsEvent.ConcurrentNicknameEvent.MODIFY_NICKNAME);//发送事件
            return;
        }
        ImageMessage headPortrait = new ImageMessage();
        headPortrait.setPath(path);
        headPortrait.setLoadStatus(MessageConstant.IMAGE_UNLOAD_AVATOR);
        Intent loadImageIntent = new Intent(context, LoadImageService.class);
        loadImageIntent.putExtra(SysConstant.UPLOAD_IMAGE_INTENT_PARAMS, headPortrait);
        context.startService(loadImageIntent);
    }


}
